package com.world.cat.controller.sys;

import com.world.cat.enums.FileType;
import com.world.cat.model.sys.PrivateFile;
import com.world.cat.pojo.UploadFileResponse;
import com.world.cat.service.sys.PrivateFileService;
import com.world.cat.app.utils.qiniu.QiniuUtil;
import com.world.cat.app.utils.qiniu.ReturnBody;
import com.world.common.pojo.Result;
import com.world.common.util.SessionUtil;
import com.world.common.util.sign.MD5Util;
import com.world.core.exception.WorldValidateException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * Created by gang on 2016/12/8.
 */
@Controller
@RequestMapping("/file")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    @Resource
    private PrivateFileService privateFileService;

    @RequestMapping(name = "文件上传", value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) throws Exception {
        Result result = new Result();
        try {
            if (file == null || file.isEmpty()) {
                result.setMsg("上传文件为空");
                return result;
            }
            String fileName = file.getOriginalFilename();
            if (StringUtils.isBlank(fileName)) {
                fileName = MD5Util.md5(UUID.randomUUID().toString());
            }
            String filePathPrefix = QiniuUtil.getQiniuPathPrefix();
            //文件上传七牛
            ReturnBody returnBody = QiniuUtil.privateBucketFileUploadByByteArr(file.getBytes(), filePathPrefix + fileName);
            //文件存在本地
            QiniuUtil.saveLocalPrivateFile(file, filePathPrefix, fileName);
            //保存文件记录
            PrivateFile privateFile = privateFileService.savePrivateFile(SessionUtil.getUserName(), returnBody, filePathPrefix, fileName);
            result.setSuccess(true);
            UploadFileResponse data = new UploadFileResponse(privateFile);
            result.setData(data);
            return result;
        } catch (WorldValidateException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("file.upload. error:", e);
            result.setMsg(e.getMessage());
        }
        return result;
    }


    @RequestMapping(name = "文件上传并创建关联关系", value = "/uploadAndLink")
    @ResponseBody
    public Object uploadAndLink(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
        String className = request.getParameter("className");
        String objId = request.getParameter("objId");
        Result result = new Result();
        try {
            if (file == null || file.isEmpty()) {
                result.setMsg("上传文件为空");
                return result;
            }
            String fileName = file.getOriginalFilename();
            if (StringUtils.isBlank(fileName)) {
                fileName = MD5Util.md5(UUID.randomUUID().toString());
            }
            String filePathPrefix = QiniuUtil.getQiniuPathPrefix();
            //文件上传七牛
            ReturnBody returnBody = QiniuUtil.privateBucketFileUploadByByteArr(file.getBytes(), filePathPrefix + fileName);
            //文件存在本地
            QiniuUtil.saveLocalPrivateFile(file, filePathPrefix, fileName);
            //保存文件记录
            PrivateFile privateFile = privateFileService.savePrivateFile(SessionUtil.getUserName(), returnBody, filePathPrefix, fileName, FileType.DOC, objId);
            result.setSuccess(true);
            UploadFileResponse data = new UploadFileResponse(privateFile);
            result.setData(data);
            return result;
        } catch (WorldValidateException e) {
            result.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("file.upload. error:", e);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping(name = "文件下载", value = "/downLoad")
    public String downLoad(HttpServletRequest request, HttpServletResponse response, String fileKey) throws Exception {
        String failMsg = "";
        try {
            String username = SessionUtil.getUserName();
            logger.info("username:[{}]下载了文件,,文件fileKey:[{}]", new Object[]{username, fileKey});

            PrivateFile privateFile = privateFileService.getPrivateFileByFileKey(fileKey);
            if (privateFile == null) {
                throw new WorldValidateException("下载的文件不存在");
            }
            return "redirect:" + QiniuUtil.getPrivateDownFileUrl(privateFile.getQiniuFilePath(), true, null);
        } catch (WorldValidateException e) {
            failMsg = e.getMessage();
        } catch (Exception e) {
            logger.error("file.download. error:", e);
            failMsg = "网络异常";
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String filename = "文件下载失败.txt";
            response.setContentType("text/plain;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            os.write(failMsg.getBytes());
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }

    @RequestMapping(name = "文件下载", value = "/downLoadById")
    public String downLoadById(HttpServletRequest request, HttpServletResponse response, String fileId) throws Exception {
        String failMsg = "";
        try {
            String username = SessionUtil.getUserName();
            logger.info("username:[{}]下载了文件,,文件fileId:[{}]", new Object[]{username, fileId});

            PrivateFile privateFile = privateFileService.getPrivateFileByFileId(fileId);
            if (privateFile == null) {
                throw new WorldValidateException("下载的文件不存在");
            }
            return "redirect:" + QiniuUtil.getPrivateDownFileUrl(privateFile.getQiniuFilePath(), true, null);
        } catch (WorldValidateException e) {
            failMsg = e.getMessage();
        } catch (Exception e) {
            logger.error("file.download. error:", e);
            failMsg = "网络异常";
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String filename = "文件下载失败.txt";
            response.setContentType("text/plain;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            os.write(failMsg.getBytes());
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }
        return null;
    }

}
